package com.wsz.utils;

//数据库连接工具类的编写
/**
 * author wsz
 * time 2022-11-23 10:21
 */

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class JdbcUtils {
    private JdbcUtils(){};

    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    private static Connection con;

    /**
     * driverClass: mysql-connector-java的驱动类名
     * url:具体连接的数据库地址端口号和其连接参数
     * Username：数据库用户名
     * Password：数据库密码
     * Connection：与特定数据库的连接（会话）
     */

    static {
        try {
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties prop = new Properties();

            prop.load(is);

            driverClass = prop.getProperty("jdbc.driver");
            url = prop.getProperty("jdbc.url");
            username = prop.getProperty("jdbc.username");
            password = prop.getProperty("jdbc.password");


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try{
            con = DriverManager.getConnection(url,username,password);
        }catch (Exception e)
        {
            e.printStackTrace();
        }

        return con;
    }

    public static void close(Connection con, Statement sta, ResultSet res){
        if(con != null)
        {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(sta != null)
        {
            try {
                sta.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(res != null)
        {
            try {
                res.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void close(Connection con, Statement sta){
        if(con != null)
        {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(sta != null)
        {
            try {
                sta.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void close(Connection con){
        if(con != null)
        {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

